// appUtils.js
const fs = require('fs');
const path = require('path');
const { WebServer } = require('../server');
const { MapsWindowManager } = require('./captureUtils');
const { getUserDataPath } = require('./fileUtils');

// 判断是否是electron环境
const ELECTRON_ENV = process.env.ELECTRON_ENV;
if (ELECTRON_ENV) {
    const { dialog } = require('electron');
}

// 初始化app，包括连接数据库，启动本地server
async function initApp(app) {
    // 创建用户数据目录
    app.userDataPath = getUserDataPath('labelmap');

    // 创建用户数据目录
    const dirs = ['', 'captures'];
    for (const dir of dirs) {
        const dirPath = path.join(app.userDataPath, dir);
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true });
        }
    }

    // 正式启动服务
    console.log('\n##====================================');
    console.log('## Starting App...');

    // 启动本地服务
    try {
        if (!app.server) {
            app.server = new WebServer(app, 3000);
            await app.server.start();
        }
    } catch (error) {
        console.error(`Can not initialize Local Web Server, Error: `, error);
        if (ELECTRON_ENV) {
            dialog.showErrorBox('Web Server Error: ', error);
            app.quit();
        }
        return;
    }

    // 创建地图窗口对象
    app.mapwnd = new MapsWindowManager(app);

    console.log('## Start App OK');
    console.log('##====================================\n');
}

// 关闭app，包括断开数据库，关闭本地server
async function closeApp(app) {
    if (app.server == null) {
        return;
    }
    if (app.isClosing) {
        return;
    }

    // 设置为正在关闭状态
    app.isClosing = true;
    console.log('\n##====================================');
    console.log('## Closing App...');
    try {
        // 关闭本地服务
        try {
            app.server && (await app.server.close());
            app.server = null;
        } catch (error) {
            console.error(`Close Local Web Server, Error: `, error);
        }

        // 关闭程序完成
        console.log('## Close App OK!');
        console.log('##====================================\n');
    } catch (err) {
        console.error('Error during app shutdown:', err);
    } finally {
        app.isClosing = false;
    }
}

module.exports = { initApp, closeApp };
